<template>
	<view>
		
	<scroll-view scroll-y="true" class="baseview basebottom">
	
	<view class="content flex-wrap flex-direction-row" style="margin-top: 0px;" 
	@click="editAddress">
	    <image src="../../../static/location.png" id="locationImg"/>
	    <view class="flex-wrap flex-direction-col"  >
	        <text>{{addrname}}  {{addrphone}}</text>
	        <text class="detail">{{addrdetail}}</text>
	    </view>
	</view>
	
	<mx-date-picker :show="showPicker" type="date" @confirm="confirm" @cancel="confirm" />
	
	<view class="date-view flex-wrap flex-direction-row" @tap="DatePicker()">
		<view class="text" style="width: 110px;">计划收货时间:</view>
		<view class="text text-grey" style="white-space:pre-wrap;" v-text="dateInfo"></view>
		<image class="text-arrow" src="../../../static/downblack.png"></image>
	</view>
	
	<!--order list-->
	<view class="content no-top-padding">
			<block v-for="(item,index) in orderList" :key="index">
				<view class="dish flex-wrap flex-direction-row">
	                <image class ="dishphoto" :src="[fromCart==1? 
					item.goodsInfo[0].goodsImages.path : item.goodsImages.path]"/>
	                <view class="flex-item">
	                    <text class="title">{{fromCart==1? item.goodsInfo[0].name: item.name}}</text>
	                    <view class="flex-wrap flex-direction-row" > 
	                        <text class="price">￥{{fromCart==1?
							item.goodsInfo[0].goodsPrice.price/100 : item.goodsPrice.price/100}}</text>
	                        <text class="quantity">x{{item.number}}</text> 
	                    </view>
	                </view>
	                
				</view>
			</block>
	</view>
	
	<!--pay style-->
	<!--<view class="content">
	    <radio-group class="flex-wrap flex-direction-row" bindchange="radioChange">
	        <label class="radio flex-item" wx:for="{{payStyles}}">
	            <radio value="{{item.name}}" checked="{{item.checked}}"/>{{item.value}}
	        </label>
	    </radio-group>
	</view>-->
	
	<!--backup message-->
	<!-- <view class="content flex-wrap flex-direction-row" bindtap="noteDetail">
	    <text class="backuptext">备注</text>
	    <text class="backup">{{ordernote}}</text>
	</view> -->
	
	<!--end of scroll-view-->
	</scroll-view>
	
	<!--commit bar-->
	<view class="cart">
	    <text class="common table">总计 </text>
		<text class="common total">￥{{total}}</text>
		<view class="common button" @click="confirmOrder">确定下单</view>
	</view>
	</view>
</template>

<script>
	import MxDatePicker from "@/components/mx-datepicker/mx-datepicker.vue"
	export default {
		components: {
			MxDatePicker,
		},
		data() {
			return {
				total: 0,
				// hidden: true,  //风车图标是否显示
				orderList: [],
				addrname: '请添加收货地址',
				addrphone: '',
				addrdetail: '',
				addrnote: '',
				fromCart: 1,
				
				showPicker: false,
				dateInfo:'最早提前五天'
			}
		},
		onLoad(options) {
				this.fromCart= options.fromCart
				this.orderList= JSON.parse(decodeURIComponent(options.orderlist))
			    this.total= options.totalMoney
		},
		onShow() {
			  let that = this
			    uni.getStorage({
			      key: 'address',
			      success: function (res) {
			        let addrs = res.data
			        if (addrs.length > 0) {
			          let address = addrs[0]
			            that.addrname= address.name
			            that.addrphone= address.phone
			            that.addrdetail= address.detail
			            that.addrnote= address.note
			        } else {
			            that.addrname= '请添加收货地址'
			            that.addrphone= ''
			            that.addrdetail= ''
			            that.addrnote= ''
			        }
			      }
			    })
		},
		methods: {
			
			DatePicker(){ this.showPicker = true },
			
			confirm(e) {
				this.showPicker = false	
				var time = e.value + ''
				var timeformat = time.replace(/\//g,"-")
				var qualifyDate = this.$uniApi.getAnyDate(new Date(), 5).fullDate
				if (qualifyDate > timeformat){
					this.$uniApi.tipMsg("最早只能提前五天预定")
					return
				}
				this.dateInfo = timeformat
			},
			
			editAddress() {
			    uni.navigateTo({ url: '../address/address' })
			},
			  talkToCustomer(title, message, isBack) {
			    uni.showModal({
			      title: title,
			      showCancel: false,
			      content: message,
			      success: function (res) {
			        if (res.confirm && isBack) { uni.navigateBack({}) }
			      }
			    })
			  },
			  
			  delCartItemById: function(id){
			    let that = this
			    uni.request({
			      url: that.$common.serverAddr +'/sales/cart/del/'+id,
			  	  method: 'POST'
			    })
			  },
			  
			  addDish2DataBaser(orderid){
				  let that = this
				  var list = []
				  var ids = []
				  for (let dish of that.orderList) {
				  	if(that.fromCart == 1) {
				  		that.delCartItemById(dish.id)
				  		ids.push(dish.id)
						list.push({ "productName":dish.goodsInfo[0].name, "productId":dish.productId, "status": 2,
									"orderId":orderid,"qty":dish.number, "unit":dish.unit, "price":dish.goodsInfo[0].goodsPrice.price,
									"subtotal":this.$uniApi.accMul(dish.goodsInfo[0].goodsPrice.price, dish.number)})
				  	}else{
						list.push({ "productName":dish.name, "productId":dish.id, "status": 2, 
									"orderId":orderid, "qty":dish.number, "unit":dish.unit, "price":dish.goodsPrice.price,
									"subtotal":this.$uniApi.accMul(dish.goodsPrice.price, dish.number)})
					}
				  }
				  uni.request({
				    url: that.$common.serverAddr+ '/sales/order/items/batch/add',
				    data: list,
				    method: 'POST',
				    success: function (res) {
				      console.log(res)
				      if (res.statusCode= 200) {
				  		that.talkToCustomer('下单成功', '', true)
				      } else {
				        that.talkToCustomer('服务器出错', '请联系客服', true)
				      }
				    },
				    fail: function () {
				      that.talkToCustomer('请稍后重试', '网络连接失败', false)
				    }
				  })
			  },
			
			  addOrder2DataBase(){
			    let that = this
				var cid = uni.getStorageSync("userid")
				if (cid == ''){
					that.talkToCustomer('您还没有登录', '请先登录', true)
					return
				}
			    uni.request({
			      url: that.$common.serverAddr+ '/sales/order/info/add',
			      data: {
			        "wsId":1, "type":"B", "customerId":cid, "origin":"APP",
					"expectTime": this.dateInfo,
					"total":this.$uniApi.accMul(that.total, 100)
			      },
			      method: 'POST',
			      success: function (res) {
			        console.log(res)
			        if (res.statusCode= 200) {
						that.addDish2DataBaser(res.data.data.orderid)
			        } else {
			          that.talkToCustomer('服务器出错', '请联系客服', true)
			        }
			      },
			      fail: function () {
			        that.talkToCustomer('请稍后重试', '网络连接失败', false)
			      }
			    })
			  },
			
			  confirmOrder() {
			    let that = this
			    uni.showModal({
			      title: '确定下单？',
			      success: function (res) {
			        if (res.confirm) { that.addOrder2DataBase() }
			      }
			    })
			  },
			
		}
	}
</script>

<style>
@import url("order.css");
</style>
